package com.xchen.imweb.message;

import com.xchen.imweb.auth.UserHolder;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.DateUtils;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@ServerEndpoint(value = "/websocket/chat", configurator = HttpSessionConfig.class)
public class ImWebSocket {

	HttpSession httpSession;

	@OnOpen
	public void onOpen(Session session, EndpointConfig config) {
		httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
		String username = UserHolder.getUsername(httpSession);
		WebSocketSession.register(username, session);
		try {
			String realName = UserHolder.getUsername(httpSession);
			String message = "系统消息: 欢迎" + realName + "加入聊天室！";
			Message.groupSend(httpSession, message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//关闭连接时调用
	@OnClose
	public void onClose() throws IOException {
		String username = UserHolder.getUsername(httpSession);
		WebSocketSession.remove(username);
		Message.groupSend(httpSession, "系统消息: " + username + "离开了聊天室！");
	}

	//收到客户端信息
	@OnMessage
	public void onMessage(Session session, String message) throws IOException {
		String realName = UserHolder.getUsername(httpSession);
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
		String time = dateFormat.format(date);
		Message.groupSend(httpSession, "[" + time + "] " + realName + ": " + message);
	}

	//错误时调用
	@OnError
	public void onError(Session session, Throwable throwable) throws IOException {
		throwable.printStackTrace();
	}

}
